#!/bin/sh

#
# Test that writing a zero-length file truncates
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

EMPTY=$WORK/empty
touch $EMPTY

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77238)

file-resource 1K.bin {
	host-path = "${TESTFILE_1K}"
}
file-resource empty {
	host-path = "${EMPTY}"
}

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
task creates-file {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
        on-resource empty {
                fat_write(\${BOOT_PART_OFFSET}, "empty")
        }
}
task truncates-file {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
        on-resource 1K.bin {
                fat_write(\${BOOT_PART_OFFSET}, "empty")
        }
        on-resource empty {
                fat_write(\${BOOT_PART_OFFSET}, "empty")
        }
}
task truncates-file2 {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
        on-resource 1K.bin {
                fat_write(\${BOOT_PART_OFFSET}, "empty")

                # This internally closes the empty file and forces a
                # separate code path for truncation.
                fat_touch(\${BOOT_PART_OFFSET}, "something_else")
                fat_rm(\${BOOT_PART_OFFSET}, "something_else")
        }
        on-resource empty {
                fat_write(\${BOOT_PART_OFFSET}, "empty")
        }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE

EXPECTED_OUTPUT=$WORK/expected.out
ACTUAL_OUTPUT=$WORK/actual.out

cat >$EXPECTED_OUTPUT << EOF
 Volume in drive : has no label
 Volume Serial Number is 0022-2DB6
Directory for ::/

empty                0 1980-01-01   0:00
        1 file                    0 bytes
                         38 910 464 bytes free

EOF

# Check that the file gets created if it's not there before
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t creates-file
mdir -i $WORK/fwup.img@@32256 > $ACTUAL_OUTPUT
diff -w $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check that the file gets truncated if it exists
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t truncates-file
mdir -i $WORK/fwup.img@@32256 > $ACTUAL_OUTPUT
diff -w $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check the FAT file format using fsck
dd if=$WORK/fwup.img skip=63 of=$WORK/vfat.img
$FSCK_FAT $WORK/vfat.img

# Check that that the code path that truncates a file on
# open works.
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t truncates-file2
mdir -i $WORK/fwup.img@@32256 > $ACTUAL_OUTPUT
diff -w $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
